# $Id: dbtable.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import optparse
import sys

from django.conf import settings
from django.db import models
from djanet.tools.lib import getopts

try:
   from djanet.tools.lib import sql
except ImportError as err:
   print(err.message)
   sys.exit(1)

class Command(getopts.GetOptions):
   option_list = (
         optparse.make_option("-d", "--db", type = "str",
            help = "database to use, default: default", default = "default",
            dest = "db"),
         optparse.make_option("-D", "--delete", type = "str",
            help = "database table to delete", dest = "table"),
   ) + getopts.GetOptions.option_list

   def __init__(self):
      super(Command, self).__init__()
      self.prog = __file__.split("/")[-1]
      self._sqlhandle = None
      self._tables = []

   def sqltype(self, engine):
      retval = None
      if engine.find("mysql") >= 0:
         retval = "MYSQL"
      elif engine.find("sqlite") >= 0:
         retval = "SQLITE"

      return retval

   def setupsql(self, sqldict = {}):
      if sqldict:
         try:
            if self.sqltype(sqldict["ENGINE"]) == "MYSQL":
               self._sqlhandle = sql.mysql(sqldict["NAME"],
                     sqldict["HOST"], sqldict["USER"], sqldict["PASSWORD"])
         except sql.SQLError as err:
            self.error(err.message)

   def handle(self, *args, **options):
      table = options.get("table")
      db = options.get("db")

      if hasattr(settings, "DATABASES"):
         if db in settings.DATABASES:
            self.setupsql(settings.DATABASES[db])

      if self._sqlhandle:
         self._tables = self._sqlhandle.tables

      djtables = {}
      for ix in models.get_apps():
         name = ix.__name__
         for model in models.get_models(ix):
            if model._meta.db_table in self._tables:
               djtables[self._sqlhandle[model._meta.db_table]] = name

      # print(foo.__name__, foo.__file__, foo.__package__)
      #
      for (key, name) in djtables.items():
         if table and (table == key):
            ix._table.drop(bind = self._sqlhandle.engine)
            print("%s: %s delete from the database" %(self.prog, str(table)))
         else:
            print("%s: %s" %(name, key))
